<template>
  <div
    class="auth-code"
    :class="[codetime ? 'gary' : '', colorClass ? colorClass : '']"
    :style="sendSmsStyle"
    @click="handlerSend"
  >
    {{ !codetime ? "获取验证码" : codetime + " s" }}
  </div>
</template>
<script>
import { sendSms } from "../../service/api";
import {isPhone} from "../../util/utils";
let timer;
export default {
  name: "send-sms",
  props: {
    phone: {
      type: String
    },
    colorClass: {
      type: String
    },
    sendSmsStyle: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      codetime: 0
    };
  },
  methods: {
    handlerSend() {
      let { phone } = this;
      if (this.codetime > 0) return;
      if (!phone) {
        this.$toast("手机号码不能为空");
        return;
      }
      if (!isPhone(phone)) {
        this.$toast("手机号码不正确");
        return;
      }
      sendSms({ mobile: phone }).then(res => {
        if (res.status == 200) {
          this.$toast("发送成功");
          this.codetime = 60;
          timer = setInterval(() => {
            this.codetime--;
            if (this.codetime < 1) {
              clearInterval(timer);
              this.codetime = 0;
            }
          }, 1000);
        }
      });
    }
  },
  beforeDestroy() {
    clearInterval(timer);
  }
};
</script>

<style scoped>
.gary {
  color: #999999 !important;
}
.auth-code {
  font-size: 0.24rem;
  min-width: 1.5rem;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
